<?php
namespace app\know\controller;

use app\user\model\AssetModel;
use app\know\model\TeachingMaterialKnowledgePointModel;
use app\know\model\TeachingMaterialContentModel;
use app\know\model\TeachingMaterialNewWordModel;
use app\know\model\TeachingMaterialListenModel;
use app\know\model\TeachingMaterialGrammarModel;
use app\know\model\SysConfigModel;
use app\know\controller\AdminKnowBaseController;
use app\know\validate\ChapterValidate;
use app\know\validate\TeachingMaterialNewWordValidate;
use app\know\validate\TeachingMaterialContentValidate;
use app\know\validate\TeachingMaterialListenValidate;
use app\know\validate\TeachingMaterialKnowledgePointValidate;
use app\know\validate\TeachingMaterialGrammarValidate;

/**
 * Class AdminTeachingMaterialContentController 教材内容控制器
 * @package app\know\controller
 */
class AdminTeachingMaterialContentController extends AdminKnowBaseController
{
    /**
     * 教材内容
     * @adminMenu(
     *     'name'   => '教材内容',
     *     'parent' => 'know/AdminTeachingMaterial/index',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 31300,
     *     'icon'   => '',
     *     'remark' => '教材内容',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_teaching_material_content_index_view');

        if (!empty($content)) {
            return $content;
        }
		$type = $this->request->param('type', 'SUBJECT');
		$this->assign('type', $type);
		
        return $this->fetch();
    }
    
    public function getItem()
    {
        $material_uuid = $this->request->param('material_uuid', '');
        $chapter_uuid = $this->request->param('chapter_uuid', '');

        $wh = ['material_uuid' => $material_uuid, 'chapter_uuid' => $chapter_uuid, 'is_delete' => 0];
        $row = TeachingMaterialContentModel::where($wh)->find();
        if ($row)
        {
            $row['content'] = $this->htmlDecode($row['content']);
            $row['eng_chn'] = $this->htmlDecode($row['eng_chn']);
            $row['teaching_reference'] = $this->htmlDecode($row['teaching_reference']);
            if ($row['audio_asset_id'])
            {
                $audio_asset = AssetModel::find($row['audio_asset_id']);
                $row['audio_asset_url'] = $audio_asset ? cmf_get_file_download_url($audio_asset["file_path"]) : '';
            }
            else
            {
                $row['audio_asset_url'] = ''; 
            }

            if ($row['new_word_asset_id'])
            {
                $word_asset = AssetModel::find($row['new_word_asset_id']);
                $row['new_word_asset_url'] = $word_asset ? cmf_get_file_download_url($word_asset["file_path"]) : '';
            }
            else
            {
                $row['new_word_asset_url'] = ''; 
            }

            $wh_l = ['material_uuid' => $material_uuid, 'chapter_uuid' => $chapter_uuid, 'is_delete' => 0];
            $listens = TeachingMaterialListenModel::where($wh_l)->select()->toArray();
            foreach ($listens as &$v)
            {
                if ($v['audio_asset_id'])
                {
                    $audio_asset = AssetModel::find($v['audio_asset_id']);
                    $v['audio_asset_url'] = $audio_asset ? cmf_get_file_download_url($audio_asset["file_path"]) : '';
                }
                else
                {
                    $v['audio_asset_url'] = ''; 
                }
            }
            $row['listen'] = $listens;
			
			$wh_g = ['a.material_uuid' => $material_uuid, 'a.chapter_uuid' => $chapter_uuid];
			$model_grammar = new TeachingMaterialGrammarModel();
			$grammars = $model_grammar->where($wh_g)
						->alias('a')
						->leftJoin('cmf_know_grammar b', 'a.grammar_uuid = b.uuid')
						->field('b.*')
						->select();
            $row['grammar'] = $grammars;
        }

        $this->success('', null, $row);
    }

	public function save()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];

        try 
        {
            $d = TeachingMaterialContentModel::where([
                'material_uuid' => $param['material_uuid'],
                'chapter_uuid' => $param['chapter_uuid'],
            ])->find();

            // 处理课文信息
            if (empty($d) === false)
            {
                TeachingMaterialContentModel::update($param, ['id' => $d['id']], TeachingMaterialContentModel::$UpdateField);
                $model = new TeachingMaterialContentModel();
                $this->opLog([
                    'table_name' => $model->getTableName(),
                    'sql' => TeachingMaterialContentModel::getLastSql(),
                    'create_user' => $user['user_login'],
                    'before_data' => json_encode($d),
                ]);
            }
            else
            {
                $model = new TeachingMaterialContentModel();
                $param['uuid'] = $model->getUUID();
                $this->validateFailError($param, 'TeachingMaterialContent.add');

                $row = TeachingMaterialContentModel::create($param);
                if ($row) 
                {
                    $this->opLog([
                        'table_name' => $model->getTableName(),
                        'sql' => TeachingMaterialContentModel::getLastSql(),
                        'create_user' => $user['user_login'],
                    ]);
                    $this->success('添加成功');
                }
            }
            // 处理课文信息

            // 词汇信息
            $arr = array_filter(preg_split("/[\s;,]/", $param['new_word_uuids']), function ($v) {
                return strlen($v) > 0;
            });
            $words = TeachingMaterialNewWordModel::where([
                'material_uuid' => $param['material_uuid'],
                'chapter_uuid' => $param['chapter_uuid'],
            ])->select()->toArray();

			$arr_a_w = [];
            foreach ($arr as $nw_id)
            {
                $ext = false;
                foreach ($words as $w)
                {
                    if ($w['new_word_uuid'] === $nw_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
                    $item['material_uuid'] = $param['material_uuid'];
                    $item['chapter_uuid'] = $param['chapter_uuid'];
                    $item['new_word_uuid'] = $nw_id;
    
                    $this->validateFailError($item, 'TeachingMaterialNewWord.add');
                    array_push($arr_a_w, $item);
                }
            }
			if (count($arr_a_w) > 0)
			{
				(new TeachingMaterialNewWordModel())->saveAll($arr_a_w);
			}
			$arr_d_w = [];
            foreach ($words as $wr)
            {
                $ext = false;
                foreach ($arr as $nw_id)
                {
                    if ($wr['new_word_uuid'] === $nw_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
					array_push($arr_d_w, $wr['id']);
                }                
            }
			if (count($arr_d_w) > 0)
			{
				TeachingMaterialNewWordModel::where('id', 'in', $arr_d_w)->delete();
			}			
            // 词汇信息
			
			// 听力信息
			$arr_l = TeachingMaterialListenModel::where([
                'material_uuid' => $param['material_uuid'],
                'chapter_uuid' => $param['chapter_uuid'],
            ])->select()->toArray();
			
            $listens = json_decode(htmlspecialchars_decode($param['listen']), true);
			$model_listen = new TeachingMaterialListenModel();
			$arr_a_l = [];
			foreach ($listens as $k => $lt)
            {
                if (empty($lt['uuid']))
                {
                    unset($listens[$k]['id']);
                    $listens[$k]['material_uuid'] = $param['material_uuid'];
                    $listens[$k]['chapter_uuid'] = $param['chapter_uuid'];
					$listens[$k]['uuid'] = $model_listen->getUUID();
					$listens[$k]['create_user'] = $user['user_login'];
                    
                    $this->validateFailError($listens[$k], 'TeachingMaterialListen.add');
					array_push($arr_a_l, $listens[$k]);
                }
                else
                {
                    $listens[$k]['modify_user'] = $user['user_login'];
                    TeachingMaterialListenModel::update($lt, ['uuid' => $lt['uuid']], TeachingMaterialListenModel::$UpdateField);
                }
            }
            if (count($arr_a_l) > 0)
			{
                $this->log($arr_a_l);
				(new TeachingMaterialListenModel())->saveAll($arr_a_l);
			}
			$arr_d_l = [];
			foreach ($arr_l as $al)
            {
                $ext = false;
                foreach ($listens as $lt)
                {
                    if (empty($lt['uuid']) === false && $al['uuid'] === $lt['uuid'])
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
					array_push($arr_d_l, $al['uuid']);
                }                
            }
			if (count($arr_d_l) > 0)
			{
				TeachingMaterialListenModel::where('uuid', 'in', $arr_d_l)->delete();
			}
			// 听力信息

            // 知识点
            $arr_kp = array_filter(preg_split("/[\s;,]/", $param['knowledge_point_uuids']), function ($v) {
                return strlen($v) > 0;
            });
            $kps = TeachingMaterialKnowledgePointModel::where([
                'material_uuid' => $param['material_uuid'],
                'chapter_uuid' => $param['chapter_uuid'],
            ])->select()->toArray();

			$arr_a_kp = [];
            foreach ($arr_kp as $kp_id)
            {
                $ext = false;
                foreach ($kps as $kp)
                {
                    if ($kp['knowledge_point_uuid'] === $kp_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
                    $item['material_uuid'] = $param['material_uuid'];
                    $item['chapter_uuid'] = $param['chapter_uuid'];
                    $item['knowledge_point_uuid'] = $kp_id;
                    $item['create_user'] = $user['user_login'];
                    
                    $this->validateFailError($item, 'TeachingMaterialKnowledgePoint.add');
                    array_push($arr_a_kp, $item);
                }
            }
            $this->log($arr_a_kp);
			if (count($arr_a_kp) > 0)
			{
				(new TeachingMaterialKnowledgePointModel())->saveAll($arr_a_kp);
			}
			$arr_d_kp = [];
            foreach ($kps as $kp)
            {
                $ext = false;
                foreach ($arr_kp as $kp_id)
                {
                    if ($kp['knowledge_point_uuid'] === $kp_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
					array_push($arr_d_kp, $kp['id']);
                }                
            }
            $this->log($arr_d_kp);
			if (count($arr_d_kp) > 0)
			{
				TeachingMaterialKnowledgePointModel::where('id', 'in', $arr_d_kp)->delete();
			}
            // 知识点
			
			// 语法信息
            $arr_g = array_filter(preg_split("/[\s;,]/", $param['grammar_uuids']), function ($v) {
                return strlen($v) > 0;
            });
            $grammars = TeachingMaterialGrammarModel::where([
                'material_uuid' => $param['material_uuid'],
                'chapter_uuid' => $param['chapter_uuid'],
            ])->select()->toArray();

			$arr_a_g = [];
            foreach ($arr_g as $g_id)
            {
                $ext = false;
                foreach ($grammars as $g)
                {
                    if ($g['grammar_uuid'] === $g_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
                    $item['material_uuid'] = $param['material_uuid'];
                    $item['chapter_uuid'] = $param['chapter_uuid'];
                    $item['grammar_uuid'] = $g_id;
                    $item['create_user'] = $user['user_login'];
                    
                    $this->validateFailError($item, 'TeachingMaterialGrammar.add');
                    array_push($arr_a_g, $item);
                }
            }
			if (count($arr_a_g) > 0)
			{
				(new TeachingMaterialGrammarModel())->saveAll($arr_a_g);
			}
			$arr_d_g = [];
            foreach ($grammars as $g)
            {
                $ext = false;
                foreach ($arr_g as $g_id)
                {
                    if ($g['grammar_uuid'] === $g_id)
                    {
                        $ext = true;
                        break;
                    }
                }
                if ($ext === false)
                {
					array_push($arr_d_g, $g['id']);
                }                
            }
			if (count($arr_d_g) > 0)
			{
				TeachingMaterialGrammarModel::where('id', 'in', $arr_d_g)->delete();
			}			
            // 语法信息
        } 
        catch (ValidateException $e) 
        {
            $this->error($e->getError());
        }
        $this->success('保存成功');  
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $id = $this->request->param('id', '');
        
        try 
        {
            $this->validateFailError($param, 'TeachingMaterialContent.delete');
        } 
        catch (ValidateException $e) 
        {
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];

        try 
        {
            $model = new TeachingMaterialContentModel();
            $model->where('id', 'in', preg_split("/[\s;,]/", $id))->save(['is_delete' => 1]);
            $this->opLog([
                'table_name' => $model->getTableName(),
                'sql' => TeachingMaterialContentModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($id),
            ]);
        } 
        catch (\Throwable $th) 
        {
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
    public function maxOrder()
    {
        $order = SysConfigModel::max('order');
        $this->success('', '', $order);
    }

    public function newWord()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.material_uuid' => $material_uuid];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }

        $model = new TeachingMaterialNewWordModel();
        $count = $model->where($where)->alias('a')->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_new_word b', 'a.new_word_uuid = b.uuid')
                    ->leftJoin('cmf_asset c', 'b.audio_asset_id = c.id')
                    ->field('a.id as nid, c.file_path as audio_url, b.*')
                    ->page($pageNumber, $pageSize)
                    ->select();

        foreach ($rows as &$v)
        {
            $v['analysis'] = $this->htmlDecode($v['analysis']);
        }           

        $this->success('', null, ['total' => $count, 'rows' => $rows]);
    }

    public function knowledgePoint()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.material_uuid' => $material_uuid];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }

        $model = new TeachingMaterialKnowledgePointModel();
        $count = $model->where($where)->alias('a')->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_knowledge_point b', 'a.knowledge_point_uuid = b.uuid')
                    ->field('a.id as nid, b.*')
                    ->page($pageNumber, $pageSize)
                    ->select();
        $stars = SysConfigModel::where(['type' => 'STAR', 'is_delete' => 0])->select();

        foreach ($rows as &$v)
        {
            $v['analysis'] = $this->htmlDecode($v['analysis']);
            foreach ($stars as $st)
            {
                if ($v['star_code'] === $st['key'])
                {
                    $v['star'] = $st['value'];
                    break;
                }
            }
        }           

        $this->success('', null, ['count' => $count, 'rows' => $rows]);
    }

    public function grammar()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['a.material_uuid' => $material_uuid];
        if ($chapter_uuid)
        {
            $where['a.chapter_uuid'] = $chapter_uuid;
        }

        $model = new TeachingMaterialGrammarModel();
        $count = $model->where($where)->alias('a')->count();
        $rows = $model->where($where)
                    ->alias('a')
                    ->leftJoin('cmf_know_grammar b', 'a.grammar_uuid = b.uuid')
                    ->field('a.id as nid, b.*')
                    ->page($pageNumber, $pageSize)
                    ->select();

        foreach ($rows as &$v)
        {
            $v['analysis'] = $this->htmlDecode($v['analysis']);
        }           

        $this->success('', null, ['total' => $count, 'rows' => $rows]);
    }

}
